package com.hansheng.mvp.presenter;

import com.hansheng.mvp.ILifeCircle;
import com.hansheng.mvp.IMvpView;
import com.hansheng.mvp.MvpController;

import java.lang.ref.WeakReference;

/**
 *
 */
public abstract class LifeCircleMvpPresenter<V extends IMvpView> implements ILifeCircle {

    private WeakReference<V> weakReference;
    
    protected LifeCircleMvpPresenter() {
        super();
    }

    public LifeCircleMvpPresenter(IMvpView iMvpView) {
        super();
        attachView(iMvpView);
        MvpController mvpControler = iMvpView.getMvpControler();
        mvpControler.savePresenter(this);
    }

    @Override
    public void attachView(IMvpView iMvpView) {
        if (weakReference == null) {
            weakReference = new WeakReference(iMvpView);
        } else {
            V view = (V) weakReference.get();
            if (view != iMvpView) {
                weakReference = new WeakReference(iMvpView);
            }
        }
    }

    @Override
    public void onDestroy() {
        weakReference = null; 
    }
    
    protected V getView() {
        V view = weakReference != null ? (V) weakReference.get() : null;
        if (view == null) {
            return getEmptyView();
        }
        return view;
    }

    protected abstract V getEmptyView();

}
